/**
 * 构建导航目录
 * @returns 
 */
function buildToc() {
    var div = document.createElement('div');
    div.style.position = 'fixed';
    div.style.right = '0px';
    div.style.top = 'calc(24% - 120px)';
    div.style.marginTop = '60px';
    div.style.width = '200px';
    div.style.padding = '10px';
    div.style.height = 'calc(60% - 120px)';
    div.style.overflow = 'overlay';
    div.style.borderLeft = "1px solid #afaaaa73";
    setDomStyle(div, {
        //"boxShadow": "rgb(249 237 223) 0px 0px 5px 3px",
        //"border": "2px solid #ebdddd",
        "backdropFilter": "blur(180px) saturate(1.5)",
        "background": "#ffffff",//repeating-linear-gradient(228deg, #f7fff8,#f8fcf9, #f5fff8 80px)
        "border": "1px solid #757171"

    })

    //下面是Chatgpt
    var div2=document.createElement('div');
    setDomStyle(div2, {
        "display": "flex",
    })
    div.appendChild(div2);
    var toTopButton = document.createElement('button');
    toTopButton.innerText = "去顶";
    div2.appendChild(toTopButton);
    toTopButton.onclick = function () {
        window.scrollTo({
            top: 0,
            behavior: 'smooth' // 平滑滚动
        })
    }
    //下面是Chatgpt
    var toMainButton = document.createElement('button');
    toMainButton.innerText = "集成页面";
    toMainButton.style.marginLeft = "10px"
    div2.appendChild(toMainButton);
    toMainButton.onclick = function () {
        window.open("main.html")
    }
    //下面是生成代码段
    var toAICodeButton = document.createElement('button');
    toAICodeButton.innerText = "AI代码生成";
    toAICodeButton.style.marginLeft = "10px"
    div2.appendChild(toAICodeButton);
    toAICodeButton.onclick = generateAICode;

    var h3=document.getElementsByClassName('subsection-title');
    var linkType=[]
    for(var i=0;i<h3.length;i++){
        var bb=h3[i].offsetTop;
        let icon=""
        if(h3[i].innerText=="成员"){
            icon="<i class='tocSignM'>M</i>"
        }
        if(h3[i].innerText=="函数"){
            icon="<i class='tocSignF'>F</i>"
        }
        if(h3[i].innerText=="Type Definitions"){
            icon="<i class='tocSignT'>T</i>"
        }
        if(h3[i].innerText=="Properties:"){
            icon="<i class='tocSignP'>P</i>"
        }
        linkType.push({
            name:h3[i].innerText,
            top:bb,
            icon:icon
        })
    }
    linkType.sort((a,b)=>{
        if(a.top<b.top)return -1;
        if(a.top>b.top)return 1;
        return 0;
    })

    var hs = document.getElementsByClassName('nameContainer');
    for (var i = 0; i < hs.length; i++) {
        var h2Item = hs[i];
        let icon="";
        var bb2=h2Item.offsetTop
        for(var j=0;j<linkType.length;j++){
            if(bb2>linkType[j].top){
                icon=linkType[j].icon;
            }
        }
        var si = document.createElement('div');
        si.innerHTML =icon+""+ h2Item.children[0].id
        if (si.innerText.length == 0) {
            continue;
        }
        si.sourceTag = h2Item;
        si.style.textIndent = (parseInt(h2Item.tagName.substr(1)) - 1) * 8 + "px";
        si.className = "toc";
        si.onclick = onTocClick;
        div.appendChild(si);
    }
    document.body.appendChild(div);
}
function setDomStyle(dom, styles) {
    for (var name in styles) {
        dom.style[name] = styles[name];
    }
}
function onTocClick(e) {
    var hi = e.target.sourceTag;
    if (hi)
        hi.getElementsByTagName('a')[0].click()
}

function generateAICode(e) {
    let result = [];
    let sections = document.querySelectorAll('.subsection-title');
    
    // Create popup window
    const popup = document.createElement('div');
    popup.style.position = 'fixed';
    popup.style.top = '50%';
    popup.style.left = '50%';
    popup.style.transform = 'translate(-50%, -50%)';
    popup.style.backgroundColor = 'white';
    popup.style.padding = '20px';
    popup.style.border = '1px solid #ccc';
    popup.style.boxShadow = '0 0 10px rgba(0,0,0,0.1)';
    popup.style.zIndex = '1000';
    popup.style.overflow="scroll";
    popup.style.height="40%";

    // Create close button
    const closeButton = document.createElement('div');
    closeButton.innerText = 'X';
    closeButton.style.position = 'absolute';
    closeButton.style.top = '5px';
    closeButton.style.right = '10px';
    closeButton.style.cursor = 'pointer';
    closeButton.style.fontWeight = 'bold';
    closeButton.style.color = '#666';
    closeButton.onclick = () => popup.remove();
    popup.appendChild(closeButton);

    // Create table
    const table = document.createElement('table');
    table.style.borderCollapse = 'collapse';
    table.style.width = '100%';
    table.style.marginBottom = '20px';

    // Create table header
    const headerRow = document.createElement('tr');

    const idHeader = document.createElement('th');
    idHeader.innerText = 'ID';
    idHeader.style.border = '1px solid #ccc';
    idHeader.style.padding = '8px';
    headerRow.appendChild(idHeader);

    const funcNameHeader = document.createElement('th');
    funcNameHeader.innerText = '函数名称';
    funcNameHeader.style.border = '1px solid #ccc';
    funcNameHeader.style.padding = '8px';
    headerRow.appendChild(funcNameHeader);

    const contentHeader = document.createElement('th');
    contentHeader.innerText = '内容';
    contentHeader.style.border = '1px solid #ccc';
    contentHeader.style.padding = '8px';
    headerRow.appendChild(contentHeader);

    table.appendChild(headerRow);

    // Generate 10-digit ID based on func
    const generateID = (func) => {
        let hash = 0;
        for (let i = 0; i < func.length; i++) {
            hash = ((hash << 5) - hash) + func.charCodeAt(i);
            hash = hash & hash; // Convert to 32bit integer
        }
        return Math.abs(hash).toString().padStart(10, '0');
    };
    const appendRowItem=(func,des)=>{
        const dataRow = document.createElement('tr');

        const idCell = document.createElement('td');
        idCell.style.border = '1px solid #ccc';
        idCell.style.padding = '8px';
        idCell.style.textAlign = 'center';
        idCell.innerText = generateID(func);
        dataRow.appendChild(idCell);

        const funcCell = document.createElement('td');
        funcCell.style.border = '1px solid #ccc';
        funcCell.style.padding = '8px';
        funcCell.style.textAlign = 'center';
        funcCell.innerText = func;
        dataRow.appendChild(funcCell);

        const contentCell = document.createElement('td');
        contentCell.style.border = '1px solid #ccc';
        contentCell.style.padding = '8px';
        contentCell.style.textAlign = 'center';
        contentCell.innerText =des;
        dataRow.appendChild(contentCell);

        table.appendChild(dataRow);
    }

    // Create submit button
    const submitButton = document.createElement('button');
    submitButton.innerText = '导出';
    submitButton.style.padding = '8px 16px';
    submitButton.style.backgroundColor = '#007bff';
    submitButton.style.color = 'white';
    submitButton.style.border = 'none';
    submitButton.style.borderRadius = '4px';
    submitButton.style.cursor = 'pointer';
    submitButton.onclick = () => {
        const rows = table.querySelectorAll('tr');
        let content = '';
        // Skip the header row and process data rows
        for (let i = 1; i < rows.length; i++) {
            const cells = rows[i].querySelectorAll('td');
            if (cells.length > 2) {
                content += cells[2].innerText + '\n';
            }
        }
        // Create a blob with the content
        const blob = new Blob([content], { type: 'text/plain' });
        // Create a link element
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'exported_content.txt';
        // Trigger the download
        document.body.appendChild(link);
        link.click();
        // Clean up
        document.body.removeChild(link);
    };

    // Add elements to popup
    popup.appendChild(table);
    popup.appendChild(submitButton);

    // Add popup to document
    document.body.appendChild(popup);

    sections.forEach(section => {
        let currentElement = section.nextElementSibling;
        let func = '';
        let desc = '';
        let params = [];
        let example = '';
        let returns=undefined;

        while (currentElement && !currentElement.classList.contains('subsection-title')) {
            if (currentElement.classList.contains('nameContainer')) {
                if (func!='') {
                    let paramText = params.length > 0 ? ";参数包括:"+params.join(', ') : '';
                    paramText = paramText.replaceAll("optional\n", "(可选的)");
                    let exampleText = example ? `;示例代码：${example}` : '无示例代码';
                    let returnsText=returns?`;返回值是json格式，内容包括:${returns}`:"";
                    console.log(`${desc}, 可以使用Barium.Commands类的${func}方法${paramText}${returnsText}${exampleText}`);
                    appendRowItem(func,`${desc}, 可以使用Barium.Commands类的${func}方法${paramText}${returnsText}${exampleText}`)
                    params=[];
                    returns=undefined;
                }

                func = currentElement.innerText.trim().split('\n')[0]
            }
            else if (currentElement.classList.contains('description')) {
                desc = currentElement.innerText;
            }
            else if(currentElement.innerText=='Returns:'){
                returns=currentElement.nextElementSibling.innerText
            }
            else if (currentElement.classList.contains('params')) {
                currentElement.querySelectorAll('tr').forEach(row => {
                    let name = row.querySelector('.name code')?.innerText.trim() || '';
                    let type = row.querySelector('.type .param-type')?.innerText.trim() || '';
                    let description = row.querySelector('.description')?.innerText.trim() || '';
                    
                    
                    // Handle nested parameter tables
                    const nestedTable = row.querySelector('.description table.params');
                    if (nestedTable) {
                        nestedTable.querySelectorAll('tr').forEach(nestedRow => {
                            let nestedName = nestedRow.querySelector('.name code')?.innerText.trim() || '';
                            let nestedType = nestedRow.querySelector('.type .param-type')?.innerText.trim() || '';
                            let nestedDesc = nestedRow.querySelector('.description')?.innerText.trim() || '';
                            if (nestedName) {
                                //params.push(`${name}.${nestedName}: ${nestedType} - ${nestedDesc}`);
                            }
                        });
                    } else if (name) {
                        params.push(`${name}: ${type} - ${description}`);
                    }
                });
            }
            else if (currentElement.classList.contains('details')) {
                example =currentElement.children.length>=2?currentElement.children[1].innerText:"";
            }
            
            currentElement = currentElement.nextElementSibling;
        }
        if (func!='') {
            let paramText = params.length > 0 ? ";参数包括:"+params.join(', ') : '';
            paramText = paramText.replaceAll("optional\n", "(可选的)");
            let exampleText = example ? `;示例代码：${example}` : '无示例代码';
            let returnsText=returns?`;返回值是json格式，内容包括:${returns}`:"";
            console.log(`${desc}, 可以使用Barium.Commands类的${func}方法${paramText}${returnsText}${exampleText}`);
            appendRowItem(func,`${desc}, 可以使用Barium.Commands类的${func}方法${paramText}${returnsText}${exampleText}`)
            params=[];
        }
    });
}

setTimeout(()=>{
    buildToc();
},500)